package com.yihukurama.gencode.service.impl;

import com.yihukurama.base.app.utils.LogUtil;
import com.yihukurama.gencode.GenCodeConstant;
import com.yihukurama.gencode.base.*;
import com.yihukurama.gencode.service.IGenEntity;
import com.yihukurama.gencode.ReplaceFileString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.List;


public class GenEntity implements IGenEntity {


    ReplaceFileString rfs = new ReplaceFileString();

    @Override
    public int genEntity(Table table) {
        if (table == null || table.getColumns() == null) {
            return 0;
        }

        Entity entity = table2Entity(table);
        File entityFile = null;
        String tableName = table.getName();

        entityFile = new File(GenCodeConstant.GENENTITYFILE_PATH + File.separator + entity.getEntFileName());

        File path = new File(GenCodeConstant.GENENTITYFILE_PATH);
        path.mkdir();

        LogUtil.debugLog(this.getClass(), "entityFile is " + entityFile.getPath());
        File tplFile = new File(GenCodeConstant.ENTITYTPL_PATH);
        //树形结构
        if (entity.getEntColumns().contains("parentId")) {
            tplFile = new File(GenCodeConstant.ENTITYTPL_PATH);
        }

        if (!entityFile.exists()) {
            try {
                entityFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return -1;
            }
        }

        BufferedReader br = null;
        String line = null;
        StringBuffer buf = new StringBuffer();
        BufferedWriter bw = null;
        try {
            InputStreamReader read = new InputStreamReader(new FileInputStream(tplFile), "UTF-8");
            // 根据文件路径创建缓冲输入流
            br = new BufferedReader(read);

            // 循环读取文件的每一行, 对需要修改的行进行修改, 放入缓冲对象中
            while ((line = br.readLine()) != null) {

                buf.append(line).append("\r\n");

            }

            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(entityFile), "UTF-8");
            // 根据文件路径创建缓冲输出流
            bw = new BufferedWriter(write);
            // 将内容写入文件中
            bw.write(buf.toString());

        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } finally {
            // 关闭流
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                }
            }
            // 关闭流
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    bw = null;
                }
            }
        }

        rfs.replacePackage(entityFile.getAbsolutePath(), "${package}", entity.getPackages());
        rfs.replacePackage(entityFile.getAbsolutePath(), "${entDesc}", entity.getEntDesc());
        rfs.replacePackage(entityFile.getAbsolutePath(), "${tableName}", table.getName());
        rfs.replacePackage(entityFile.getAbsolutePath(), "${entityName}", entity.getEntName());
        rfs.replacePackage(entityFile.getAbsolutePath(), "${entColumns}", entity.getEntColumns());
//      使用lobom，不需要生成get  set方法
//        rfs.replacePackage(entityFile.getAbsolutePath(), "${entGetSet}", entity.getEntGetSet());
        rfs.replacePackage(entityFile.getAbsolutePath(), "${toString}", entity.getToString());
        rfs.replacePackage(entityFile.getAbsolutePath(), "${project}", GenCodeConstant.PROJECT);

        return 1;
    }

    private Entity table2Entity(Table table) {
        Entity entity = new Entity();
        entity.setEntColumns(genEntColumns(table));
        entity.setEntDesc(genEntDesc(table));
        entity.setEntGetSet(genEntGetSet(table));
        entity.setEntName(genEntName(table));
        entity.setEntFileName(genEntFileName(table));
        entity.setPackages(GenCodeConstant.ENTITYPACKAGE);

        return entity;
    }

    @Override
    public String genEntColumns(Table table) {
        List<Column> columns = table.getColumns();
        StringBuffer entColumns = new StringBuffer();
        for (int i = 0; i < columns.size(); i++) {
            Column column = columns.get(i);
            if (column.getName().equals("id")) {
                //由于baseEntity中有id，因此这里不用生成
                continue;
            }
            entColumns.append("/**\n\t*" + column.getRemark() + "\n\t**/\n\t");
            String colName = column.getName().toLowerCase();
            if(colName.contains("_")){
                String [] colNameSplit = colName.split("_");
                colName = colNameSplit[0];
                for (int j = 1; colNameSplit.length>=1 && j <colNameSplit.length ; j++) {
                    colName += colNameSplit[j].substring(0, 1).toUpperCase() + colNameSplit[j].substring(1);
                }
            }


            if (column.getName().equals("id")) {
                entColumns.append("@Id\n\t");
                entColumns.append("private String id;\n\t");
                continue;
            }

            if (column.getType().equals("Date")) {
                entColumns.append("@JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")\n\t");
                entColumns.append("@JSONField(format=\"yyyy-MM-dd HH:mm:ss\")");
                entColumns.append("@Column(name=\"" + column.getName() + "\")\n\t");
                entColumns.append("private Date " + colName + ";\n\t");

                continue;
            }
            entColumns.append("@ApiModelProperty(value=\"" + column.getRemark() + "\")\n\t");
            entColumns.append("@Column(name=\"" + column.getName() + "\")\n\t");
            entColumns.append("private " + column.getType() + " " + colName + ";\n\t");


        }
        return entColumns.toString();
    }

    @Override
    public String genEntGetSet(Table table) {
        List<Column> columns = table.getColumns();
        StringBuffer entGetSet = new StringBuffer();
        for (int i = 0; i < columns.size(); i++) {
            String name = columns.get(i).getName();
            if(name.equals("ID")){
                continue;
            }
            String colName = name.toLowerCase();
            colName = colName.substring(0,1).toUpperCase()+colName.substring(1);
            if(colName.contains("_")){
                String [] colNameSplit = colName.split("_");
                colName = colNameSplit[0].substring(0,1).toUpperCase()+colNameSplit[0].substring(1);
                for (int j = 1; colNameSplit.length>=1 && j <colNameSplit.length ; j++) {
                    colName += colNameSplit[j].substring(0, 1).toUpperCase() + colNameSplit[j].substring(1);
                }
            }

            String columnName = colName;
            String privateName = columnName.substring(0,1).toLowerCase()+columnName.substring(1);
            String columnType = columns.get(i).getType();

            entGetSet.append("public " + columnType + " get" + columnName + "(){\n");
            if (columnType.equals("Double")) {//如果是Double类型经常用于计算设默认值0.0
                entGetSet.append("\t\treturn " + privateName + "==null?0.0:" + privateName + ";\n\t");
            } else {
                entGetSet.append("\t\treturn " + privateName + ";\n\t");
            }
            entGetSet.append("}\n");
            entGetSet.append("\n\t");

            entGetSet.append("public void set" + columnName + "(" + columnType + " " + privateName + "){\n\t");
            if (columnType.equals("Double")) {//如果是Double类型经常用于计算设默认值0.0
                entGetSet.append("\tthis." + privateName + " = " + privateName + "==null?0.0:" + privateName + ";\n\t");
            } else {
                entGetSet.append("\tthis." + privateName + " = " + privateName + ";\n\t");
            }

            entGetSet.append("}\n\n\t");
        }
        return entGetSet.toString();
    }


    @Override
    public String genEntDesc(Table table) {
        // TODO Auto-generated method stub
        return table.getRemark();
    }

    @Override
    public String genEntFileName(Table table) {
        String domainName = "";
        if(table.getName().contains("_")){
            String [] colNameSplit = table.getName().split("_");
            for (int j = 1; colNameSplit.length>=1 && j <colNameSplit.length ; j++) {
                domainName += colNameSplit[j].substring(0, 1).toUpperCase() + colNameSplit[j].substring(1);
            }
        }
        domainName = domainName.substring(0, 1).toUpperCase() + domainName.substring(1);
        String entName = domainName.substring(0, 1).toUpperCase() + domainName.substring(1) + "Entity";
        return entName + ".java";
    }

    @Override
    public String genEntName(Table table) {
        String domainName = "";
        if(table.getName().contains("_")){
            String [] colNameSplit = table.getName().split("_");
            for (int j = 1; colNameSplit.length>=1 && j <colNameSplit.length ; j++) {
                domainName += colNameSplit[j].substring(0, 1).toUpperCase() + colNameSplit[j].substring(1);
            }
        }
        domainName = domainName.substring(0, 1).toUpperCase() + domainName.substring(1);
        String entName = domainName.substring(0, 1).toUpperCase() + domainName.substring(1) + "Entity";
        return entName;
    }

    @Override
    public String genEntToString(Table table) {
        // TODO Auto-generated method stub
        return null;
    }
}
